<template>
  <div class="user-management-bg">
    <div class="user-management">
      <div class="user-header">
        <div class="user-title">
          <span class="title-bar"></span>用户管理
        </div>
        <el-button class="add-user-btn" type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          添加用户
        </el-button>
      </div>
      <el-card class="user-table-card" shadow="hover">
        <el-table :data="users" style="width: 100%" v-loading="loading" stripe border class="user-table">
          <el-table-column prop="id" label="ID" width="230" align="center" />
          <el-table-column prop="username" label="用户名" width="230" align="center" />
          <el-table-column prop="isAdmin" label="角色" width="230" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.isAdmin ? 'success' : 'info'">
                {{ scope.row.isAdmin ? '管理员' : '普通用户' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="230" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="230" align="center">
            <template #default="scope">
              <el-button-group>
                <el-button size="small" type="primary" @click="handleEdit(scope.row)" class="action-btn">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row)" class="action-btn">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="500px"
        class="user-dialog"
      >
        <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="100px" class="user-form">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" size="large" />
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="!userForm.id">
            <el-input v-model="userForm.password" type="password" size="large" />
          </el-form-item>
          <el-form-item label="角色" prop="isAdmin">
            <el-select v-model="userForm.isAdmin" size="large">
              <el-option label="管理员" :value="true" />
              <el-option label="普通用户" :value="false" />
            </el-select>
          </el-form-item>
          <el-form-item class="form-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import axios from 'axios'

const users = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const userFormRef = ref(null)

const userForm = reactive({
  id: '',
  username: '',
  password: '',
  isAdmin: false
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  isAdmin: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const fetchUsers = async () => {
  loading.value = true
  try {
    const res = await axios.get('http://localhost:3001/api/users')
    users.value = res.data
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  dialogTitle.value = '添加用户'
  Object.assign(userForm, {
    id: '',
    username: '',
    password: '',
    isAdmin: false
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  Object.assign(userForm, {
    id: row.id,
    username: row.username,
    isAdmin: row.isAdmin
  })
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该用户吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await axios.delete(`http://localhost:3001/api/users/${row.id}`)
      ElMessage.success('删除成功')
      fetchUsers()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const submitForm = async () => {
  if (!userFormRef.value) return
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (userForm.id) {
          await axios.put(`http://localhost:3001/api/users/${userForm.id}`, userForm)
          ElMessage.success('更新成功')
        } else {
          await axios.post('http://localhost:3001/api/users', userForm)
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        fetchUsers()
      } catch (error) {
        ElMessage.error(userForm.id ? '更新失败' : '添加失败')
      }
    }
  })
}

onMounted(() => {
  fetchUsers()
})
</script>

<style>
body, html {
  height: 100%;
}
.user-management-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #e3f0ff 0%, #f8fbff 100%);
  padding: 0;
  width: 100vw;
  margin: 0;
}
.user-management {
  padding: 0;
  width: 100vw;
  max-width: none;
  margin: 0;
}
.user-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding: 18px 32px 18px 24px;
  background: rgba(255,255,255,0.85);
  border-radius: 18px;
  box-shadow: 0 2px 16px 0 #1565c022;
  width: 100%;
}
.user-title {
  font-size: 2.1em;
  color: #1565c0;
  font-weight: 800;
  letter-spacing: 1px;
  display: flex;
  align-items: center;
}
.title-bar {
  display: inline-block;
  width: 6px;
  height: 32px;
  background: linear-gradient(180deg, #1565c0 60%, #42a5f5 100%);
  border-radius: 4px;
  margin-right: 16px;
}
.add-user-btn {
  font-size: 1.1em;
  padding: 12px 28px;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 #42a5f544;
  font-weight: 600;
  transition: box-shadow 0.2s, background 0.2s;
}
.add-user-btn:hover {
  background: #1976d2;
  box-shadow: 0 4px 24px 0 #42a5f577;
}
.user-table-card {
  margin-bottom: 0;
  border-radius: 0;
  box-shadow: none;
  border: none;
  background: #fff;
  width: 100vw;
  max-width: none;
  padding: 0;
}
.user-table {
  border-radius: 0;
  overflow: hidden;
  width: 100vw;
  min-width: 100vw;
  margin: 0;
}
.el-table th, .el-table td {
  font-size: 16px;
}
.el-table th {
  background: linear-gradient(90deg, #e3f0ff 60%, #f6f8fa 100%);
  color: #1565c0;
  font-weight: 700;
}
.el-table__row:hover {
  background: #e3f0ff !important;
}
.el-table .el-button-group .el-button.action-btn {
  padding: 5px 10px;
  border-radius: 8px;
  margin-left: 2px;
  margin-right: 2px;
  min-width: 32px;
  transition: background 0.2s, box-shadow 0.2s;
}
.el-table .el-button-group .el-button.action-btn:hover {
  box-shadow: 0 2px 8px #42a5f555;
  background: #e3f0ff;
}
.el-table .el-tag {
  font-size: 14px;
  border-radius: 8px;
  padding: 4px 16px;
}
.user-dialog .el-dialog__body {
  padding: 36px 44px 16px 44px;
  border-radius: 18px;
  background: #f8fbff;
}
.user-dialog .el-dialog {
  border-radius: 18px;
  box-shadow: 0 8px 32px 0 #1565c044;
}
.user-form .el-input__wrapper {
  background: #f6f8fa;
  border-radius: 12px;
  border: 1.5px solid #e3eafc;
  box-shadow: none;
  transition: border 0.2s;
  padding: 0 8px;
}
.user-form .el-input__wrapper:hover,
.user-form .el-input__wrapper.is-focus {
  border: 1.5px solid #1565c0;
}
.user-form .el-input__inner {
  height: 48px;
  font-size: 16px;
  background: transparent;
}
.form-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 18px;
}
.form-footer .el-button[type="primary"] {
  background: linear-gradient(90deg, #1976d2 60%, #42a5f5 100%);
  color: #fff;
  font-weight: 700;
  border-radius: 8px;
  padding: 0 24px;
  box-shadow: 0 2px 8px #42a5f555;
}
</style> 